// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//alert('Hello World!');

$(function() {
    // var dataURL = "http://localhost:9188";
    var dataURL = "https://xinsinfo.com:8443";
    var sessionId="";
    var layerAutoButton = '<a id="__float_layer_auto__" style =" margin: 0 20px; background-color: #2dc888; padding: 3px 8px 3px;"> 一键提取 </a>';
    var layerSubbmit = '<a id="__float_layer_submit__" style =" margin: 0 20px; background-color: #009afff5; padding: 3px 8px 3px;"> 提交 </a>';
    var layerTitle = '<h3><label  id="__login_layer__">🙂</label> <label  id="__submit_result__" style="display:none;color: #1ff976;margin-left:10px;">✔</label><span style="float: left;">'+layerAutoButton+'</span><span style="float: right;">'+layerSubbmit+'</span></h3> ';
    $("body").append('<div id="__float-layer">'+layerTitle+'<div id="__float_layer_content"></div></div>');

    var lineStr ="<p></p>";
    var selectStr ="<select style='float:left;width:80px'> <option value='1'>item标题</option> <option value='2'>SKU名称</option> <option value='3'>SKU图片</option> <option value='4'>item详描</option></select>";
    var inputStr= "<input type='text'>";
    var removeStr= "<a style='with:18px;'>X</a>";
    
    var productInfoStr ="#recyclerview";
    var productDetailStr ="#detailContentContainer";

	var __float_parent=$("#__float-layer");
	var __float_layer_content=$("#__float_layer_content");
	var __float_auto=$("#__float_layer_auto__");
	var __float_submit=$("#__float_layer_submit__");

	$(document).on("click", function(event) {
		var target = $(event.target);
		// 排除浮动层及层内的所有标签
		if (target.closest("#__float-layer").length === 0 && target.closest("body").length>0) { 
			var text;
			if (target.is("img")) {
				text = target.attr("src");
			} else {
				text = target.text();
			}
            // 判断获取的文本是否为空
			if (text) { 
                var addLine = $(lineStr);
                var selectType = $(selectStr);
				var inputText = $(inputStr);
                inputText.val(text);
				var removeBtn = $(removeStr);
				removeBtn.on('click', function() {
					addLine.remove();
				});
                addLine.append(selectType);
				addLine.append(inputText);
				addLine.append(removeBtn);
				__float_layer_content.append(addLine); 
			}
			
		}
	});

    __float_auto.on("click",function(){
        __float_layer_content.empty();
        // title
        var addLine = $(lineStr);
        var selectType = $(selectStr);  selectType.val(1);
        var inputText = $(inputStr);    inputText.val($(productInfoStr).find(".title-text").text());
        var removeBtn = $(removeStr);
        removeBtn.on('click', function() {
            addLine.remove();
        });
        addLine.append(selectType);
        addLine.append(inputText);
        addLine.append(removeBtn);
        __float_layer_content.append(addLine); 

        //sku style 平铺
        $(productInfoStr).find(".prop-item").each(function(i,e){
            // sku name
            var addLine = $(lineStr);
            var selectType = $(selectStr);  selectType.val(2);
            var inputText = $(inputStr);  inputText.val( e.textContent);
            var removeBtn = $(removeStr); 
            removeBtn.on('click', function() {
                addLine.remove();
            });
            addLine.append(selectType);
            addLine.append(inputText);
            addLine.append(removeBtn);
            __float_layer_content.append(addLine); 

             // sku img
            var addLine = $(lineStr);
            var selectType = $(selectStr);  selectType.val(3);
            var inputText = $(inputStr);  inputText.val($(e).find(".prop-img").attr("style").replace('background: url(','').split('")')[0].replace('"',''));
            var removeBtn = $(removeStr); 
            removeBtn.on('click', function() {
                addLine.remove();
            });
            addLine.append(selectType);
            addLine.append(inputText);
            addLine.append(removeBtn);
            __float_layer_content.append(addLine); 
        });
        
        //sku style 列表
        $("#sku-count-widget-wrapper > div.sku-item-wrapper").each(function(i,e){

             // sku img
            var skuImg=$(e).find("div.sku-item-image");
            if(skuImg == null || skuImg.attr("style") == null){ return ;}
            var addImgLine = $(lineStr);
            var selectType = $(selectStr);  selectType.val(3);
            var inputText = $(inputStr);  
            inputText.val(skuImg.attr("style").replace('background: url(','').split('")')[0].replace('"',''));
            var removeBtn = $(removeStr); 
            removeBtn.on('click', function() {
                addImgLine.remove();
            });
            addImgLine.append(selectType);
            addImgLine.append(inputText);
            addImgLine.append(removeBtn);

            // sku name
            var skuName=$(e).find("div > div.sku-item-name");
            var addTextLine = $(lineStr);
            var selectType = $(selectStr);  selectType.val(2);
            var inputText = $(inputStr);  inputText.val( skuName.text());
            var removeBtn = $(removeStr); 
            removeBtn.on('click', function() {
                addTextLine.remove();
            });
            addTextLine.append(selectType);
            addTextLine.append(inputText);
            addTextLine.append(removeBtn);

            __float_layer_content.append(addTextLine); 
            __float_layer_content.append(addImgLine); 

        });
         
        var detailImgs="";
        $("#detailContentContainer > div > p > a > img").each(function(i,e){
            detailImgs += $(e).attr("src")+";";
        });
        if(detailImgs===''){
            $("#detailContentContainer > div > p > img").each(function(i,e){
                detailImgs += $(e).attr("src")+";";
            });
        }
        if(detailImgs===''){
            $("img.desc-img-loaded").each(function(i,e){
                detailImgs += $(e).attr("src")+";";
            });
        }
        var addLine = $(lineStr);
        var selectType = $(selectStr);  selectType.val(4);
        var inputText = $(inputStr);  inputText.val(detailImgs);
        var removeBtn = $(removeStr); 
        removeBtn.on('click', function() {
            addLine.remove();
        });
        addLine.append(selectType);
        addLine.append(inputText);
        addLine.append(removeBtn);
        __float_layer_content.append(addLine); 

    });

    __float_submit.on("click",function(){
        let postParam={};
        let skuInfoArr =[];
        postParam.siteName = "1688";
        postParam.itemUrl = window.location.href;
        let param ={};
        __float_layer_content.children("p").each(function(i,e){
            
            let type = $(e).find("select").val();
            let val= $(e).find("input").val();
            switch(type){
                case "1":
                    postParam.itemName=val;
                    break;
                case "2":
                    param.skuName=val;
                    break;
                case "3":
                    param.skuImgUrl=val;
                    skuInfoArr.push(param)
                    param ={};
                    break;
                case "4":
                    postParam.itemDetail=val;
                    break;
            } 
        });
        postParam.skuInfo=JSON.stringify(skuInfoArr);
        console.log(JSON.stringify(postParam))
        var url = dataURL +"/chat/productInfo/addProductInfo?sessionId="+sessionId;
        $.ajax({
            type:"post",
            url:url,
            dataType:'json',
            contentType: "application/json; charset=utf-8",
            data:JSON.stringify(postParam),
            traditional:true,
            success:function(data){
                console.log(JSON.stringify(data));
                if(data.code ===200 ){
                    $("#__submit_result__").fadeIn(100);
                    $("#__submit_result__").fadeOut(5000);
                }else {
                    $("#__login_layer__").html("😐");
                    alert(data.msg)
                }
            }
        });
    });

    $("#__login_layer__").on("click",function(){
        $.get(dataURL+"/chat/account/login?p=Wenjiajia@123123123",function(data){
            if(data!=null && data.data!=null && data.data.sessionId!=null){
                sessionId=data.data.sessionId;
                $("#__login_layer__").html("😘");
            }
        });
    })

	var isDragging = false;
	var startPosition = {};
	var offset = {};
	$("#__float-layer h3").on("mousedown", function(event) { 
		isDragging = true;
		startPosition = {x: event.pageX, y: event.pageY};
		offset = __float_parent.offset();
	});

	$(document).on("mouseup", function() {
		isDragging = false;
	}).on("mousemove", function(event) {
		if (isDragging) {
			var newX = event.pageX - startPosition.x + offset.left;
			var newY = event.pageY - startPosition.y + offset.top;
			__float_parent.offset({left: newX, top: newY});
		}
	});
});
 